
// export default {
const fileUtils = (function(){

    async function processHandle(handle){
    
        if(handle.kind === 'file'){
            handle.read = read
            return handle
        }
    
        handle.children = []
        handle.forEach = forEach
    
        const iter = handle.entries()
    
        for await (const item of iter){
            handle.children.push(await processHandle(item[1]))
        }
    
        return handle
    }
    
    
    async function read(code = 'utf-8'){
        const file = await this.getFile()
        const reader = new FileReader()
        reader.readAsText(file, code)
        return await new Promise((resolve, reject) => {
            reader.onload = function (e){
                resolve({
                    file, 
                    text : e.target.result
                })
            }
        })
    }

    function forEach(fn = function(){}){
        if (typeof fn !== 'function') {
            throw new Error('必须是一个函数forEach(fn = function(){})')
        }
        let children = this.handle && this.handle.children || this.children || []
        children.forEach((n, i) => fn(n, i))
    }

    return {
        async showDirectory(){
            try{
                return await processHandle(await showDirectoryPicker())
            }catch(e){
        
            }
        },
    }
}())